package top.zhimingw.controller;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.zhimingw.pojo.Admin;
import top.zhimingw.utils.LogUtils;

import java.util.Date;

/**
 * @ClassName: LoginController
 * @Description:
 * @Author:zhimingw
 * @Version 1.0
 * @since 2021/7/6 16:10
 */
@Controller
public class LoginController extends BaseController{
    private Logger logger = LogUtils.getInstance(LoginController.class);

    /**
    * @Description: 管理员登录
    * @Param: [name, password]
    * @return: java.lang.String
    * @Author: zhimingw
    * @Date: 2021/7/6
    */
    @PostMapping("/login")
    @ResponseBody
    public String login(String name,String  password){
        // 获取管理员对象
        Admin admin = adminService.queryById(1);
        // 获取Md5加密对象
        MD5 md5 = new MD5(admin.getSalt().getBytes());
        //进行判断
        if(admin.getName().equals(name)&&admin.getPassword().equals(md5.digestHex16(password))){
            result.setCode(200);
            logger.warn("【成功】密码登录");
            admin.setRecentLogin(new Date());
            adminService.update(admin);
            session.setAttribute("admin",admin);
        }else{
            result.setCode(100);
            logger.warn("【错误】密码登录，用户名或密码错误");
        }
        return JSONObject.toJSONString(result);
    }
    
    /**
    * @Description: 退出登录
    * @Param: []
    * @return: java.lang.String
    * @Author: zhimingw
    * @Date: 2021/7/16
    */
    @GetMapping("/logout")
    public String logout(){
        session.invalidate();
        logger.warn("【成功】退出登录");
        return "redirect:/admin-login";
    }
}
